//
//  KHHTravelNotesDetailPageViewController.m
//  Travel
//
//  Created by dllo on 15/12/1.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "KHHTravelNotesDetailPageViewController.h"
#import "KHHTravelNotesDetailPageTableViewCell.h"
#import "KHHTravelNotesPageUserTableViewCell.h"
#import "KHHTravelNotesDetailLocationPageViewController.h"
#import "KHHMapViewController.h"
#import "KHHRecommendModel.h"
#import "UIImageView+WebCache.h"
#import "UIImage+GIF.h"
#import "Trave.h"
#import "CoreDataManager.h"

@interface KHHTravelNotesDetailPageViewController ()<UITableViewDataSource, UITableViewDelegate, jumpToLocationPage>

@property (nonatomic, retain)UICollectionView *collectionView;

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)KHHRecommendModel *noteModel; //包含所有信息的model
@property (nonatomic, retain)KHHRecommendModel *userModel;
@property (nonatomic, retain)NSMutableArray *modelDayArr; //保存游记具体内容总数据
@property (nonatomic, retain)NSMutableArray *modelWaypointsArr; //保存每天waypoints套对象的数组
@property (nonatomic, retain)NSMutableArray *modelLocationArr;  //保存每天的location对象

@property (nonatomic, retain) NSMutableArray *arr_result;
@property (nonatomic, strong) UIButton *btn_like;
@property (nonatomic, retain) CoreDataManager *manager;


@end

@implementation KHHTravelNotesDetailPageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addScreenEdgePan];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"游记详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"leftBack"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backToLast)];
    
    //初始化coredata单例
    self.manager = [CoreDataManager shareInstance];

    //如果是从首页的游记里跳转过来
    if (self.recommendModel) {
       
        [self selectAllLike];
        if(self.arr_result.count != 0){
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"like2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(likeAction)];
            self.navigationItem.backBarButtonItem.tintColor = [UIColor redColor];
        } else {
                
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"like1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(likeAction)];
            self.navigationItem.backBarButtonItem.tintColor = [UIColor whiteColor];
        }
    }
    [self getData];
    
    //菊花
    [CXLoadMBProgress loadMBProgress:self.view];
}

- (void)getData
{
    NSString *url = nil;
    //判断从哪个界面跳转过来 从哪个数据里取id
    if (self.tagtag == 10) {
        url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/waypoints/", self.ForthID];
    }else{
    
    if (self.locationImpressionToDetailID != nil) {
        
        url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@", self.locationImpressionToDetailID];
        
    } else {
        
        url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%ld", (long)self.travelNotesModel.notesId.integerValue];
    }
}
    
    
    [CXNetHandle getUrl:url cookie:nil result:^(id result) {
        
        //移除菊花
        [CXLoadMBProgress removeMBProgress:self.view];
       
        NSMutableDictionary *tempDic = result;
        
        self.noteModel = [[KHHRecommendModel alloc]init];
        [self.noteModel setValuesForKeysWithDictionary:tempDic]; //把当前字典转化成对象  包含所有信息
        
        self.userModel = [[KHHRecommendModel alloc]init];
        [self.userModel setValuesForKeysWithDictionary:result[@"user"]]; //用户信息model

        self.modelDayArr = [KHHRecommendModel transformWithArray:result[@"days"]];  //保存游记具体内容总数据
        
        NSMutableArray *waypointsArr = [NSMutableArray array]; //保存所有waypoints数组
        self.modelLocationArr = [NSMutableArray array];  //保存所有location的 model对象
        
        for (NSDictionary *dic in result[@"days"]) {
            
            NSMutableArray *tempWaypointArr = [NSMutableArray array];
            for (NSMutableDictionary *dic2 in dic[@"waypoints"]) {
                if (dic2[@"id"] != nil) //有的waypoints字典里并没有数据
                {
                    [tempWaypointArr addObject:dic2];
                }
                
            }
            [waypointsArr addObject:tempWaypointArr]; //数组套数组套waypoints对象
            
            
            NSMutableArray *tempArr = [NSMutableArray array];  //用来保存每天的waypoint里的location对象
            //遍历每天得waypoint数组
            for (NSMutableDictionary *dic in tempWaypointArr)
            {
                if ([dic[@"location"] class] == [NSNull class]) {
                    KHHRecommendModel *model = [[KHHRecommendModel alloc] init];
                    [tempArr addObject:model];
                }else{
                    //保存location对象
                    KHHRecommendModel *model = [[KHHRecommendModel alloc] init];
                    [model setValuesForKeysWithDictionary: dic[@"location"]];
                    [tempArr addObject:model];
                }
            }
            [self.modelLocationArr addObject:tempArr];
        }
        self.modelWaypointsArr = [NSMutableArray array];
        for (NSMutableArray *arr in waypointsArr) {
            [self.modelWaypointsArr addObject: [KHHRecommendModel transformWithArray:arr]];
        }
        
        [self createTableView];
    }];
    
}

#pragma mark - 按钮触发方法
- (void)backToLast
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, -33, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // self.tableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
    [self.view addSubview:self.tableView];
    
    
    //基类方法 改变为夜间模式颜色
   // [[self class]BoolIsNight:self.tableView];
    
    //注册cell
    [self.tableView registerClass:[KHHTravelNotesPageUserTableViewCell class] forCellReuseIdentifier:@"user"];
    [self.tableView registerClass:[KHHTravelNotesDetailPageTableViewCell class] forCellReuseIdentifier:@"notes"];
}

#pragma mark - 喜欢按钮触发方法
- (void)likeAction
{
    [self selectAllLike];
    
    if (self.arr_result.count != 0) {
        NSLog(@"已经收藏");
        //删除
        for (Trave *story in self.arr_result) {
            
            [self.manager.managedObjectContext deleteObject:story];
        }
        [self.manager saveContext];
        
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"like1"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏" message:@"取消收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        //[alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // }]];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        [self performSelector:@selector(cancelAlertAction) withObject:alert afterDelay:1.0];
        
    } else {
        //添加
        Trave *story = [NSEntityDescription insertNewObjectForEntityForName:@"Trave" inManagedObjectContext: self.manager.managedObjectContext];
        
        story.name = self.recommendModel.name;
        story.cover_image = self.recommendModel.cover_image;
        story.day_count = self.recommendModel.day_count;
        story.first_day = self.recommendModel.first_day;
        story.popular_place_str = self.recommendModel.popular_place_str;
        story.type = self.recommendModel.type;
        story.valueId = self.recommendModel.valueId;
        story.avatar_m = self.recommentUserModel.avatar_m;
        story.name = self.recommentUserModel.name;
        
        [self.manager saveContext];
        
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor redColor];
        self.navigationItem.rightBarButtonItem.image = [UIImage imageNamed:@"like2"];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"收藏" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        //[alert addAction:[UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //}]];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        [self performSelector:@selector(cancelAlertAction) withObject:alert afterDelay:1.0];
    }
 
}

//自动取消alert
- (void) cancelAlertAction {
    [self dismissViewControllerAnimated:YES completion:nil];
}


//查询数据库
- (void)selectAllLike
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Trave" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"avatar_m = %@", self.recommentUserModel.avatar_m];
    
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    
    
    //排序 参数:根据什么排序 yes 升序  / no 降序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
    }
    [self.arr_result removeAllObjects];
    self.arr_result = [NSMutableArray arrayWithArray:fetchedObjects];
}


#pragma mark - 游记详情 location跳转下一页 button协议方法
- (void)jumpToLocation:(NSIndexPath *)indexpath
{

    if ([self.modelLocationArr[indexpath.section - 1][indexpath.row] longitude] && ![self.modelWaypointsArr[indexpath.section - 1][indexpath.row]poiName]) {
        
        KHHMapViewController *map = [[KHHMapViewController alloc] init];
        map.locationModel = self.modelLocationArr[indexpath.section - 1][indexpath.row];
        map.modelWayPoints = self.modelWaypointsArr[indexpath.section - 1][indexpath.row];
        [self.navigationController pushViewController:map animated:YES];
        
    } else {
        
        KHHTravelNotesDetailLocationPageViewController *pageView = [[KHHTravelNotesDetailLocationPageViewController alloc]init];
        pageView.waypointsModel = self.modelWaypointsArr[indexpath.section - 1][indexpath.row];
        [self.navigationController pushViewController:pageView animated:YES];
    }
}

#pragma mark - tableView分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.modelWaypointsArr.count + 1;
}

#pragma mark - tableView分区头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
        
    } else {
        return 20;
    }
}
#pragma mark - tableView头部视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        
        return nil;
        
    } else {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CWIDTH, 20)];
        view.backgroundColor  = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        
        UIView *viewCircle = [[UIView alloc] initWithFrame:CGRectMake(20, -20, 20, 20)];
        viewCircle.layer.masksToBounds = YES;
        viewCircle.layer.cornerRadius = 10;
        viewCircle.backgroundColor = [UIColor colorWithRed:0.89 green:0.87 blue:0.78 alpha:1];
        [view addSubview:viewCircle];
        
        UIView *littleCircle = [[UIView alloc] initWithFrame:CGRectMake(0, -20, 10, 10)];
        littleCircle.layer.masksToBounds = YES;
        littleCircle.layer.cornerRadius = 5;
        littleCircle.center = viewCircle.center;
        littleCircle.backgroundColor = [UIColor whiteColor];
        [view addSubview:littleCircle];
        
        UIView *viewLine = [[UIView alloc]initWithFrame:CGRectMake(28, viewCircle.frame.size.height + viewCircle.frame.origin.y, 5, 20)];
        viewLine.backgroundColor = [UIColor colorWithRed:0.89 green:0.87 blue:0.78 alpha:1];
        [view addSubview:viewLine];
        
        
        UILabel *labelDay = [[UILabel alloc] initWithFrame:CGRectMake(50, -15, 50, 12)];
        labelDay.textColor = [UIColor colorWithRed:0.79 green:0.73 blue:0.6 alpha:1];
        labelDay.font = [UIFont systemFontOfSize:15];
        [view addSubview:labelDay];
        
        UILabel *labelDate = [[UILabel alloc] initWithFrame:CGRectMake(110, -15, 150, 12)];
        labelDate.textColor = [UIColor colorWithRed:0.79 green:0.73 blue:0.6 alpha:1];
        labelDate.font = [UIFont systemFontOfSize:15];
        [view addSubview:labelDate];
        
        NSNumber *day =  ((KHHRecommendModel *) self.modelDayArr[section - 1]).day;
        labelDay.text = [NSString stringWithFormat:@"%@%@%@", @"第", day, @"天"];
        
        NSString *date = ((KHHRecommendModel *) self.modelDayArr[section - 1]).date;
        labelDate.text = [date substringFromIndex:5];
        
//        //夜间模式
//        if ([[NSUserDefaults standardUserDefaults]boolForKey:@"isNight"]) {
//            view.backgroundColor = [UIColor colorWithRed:0.28 green:0.28 blue:0.28 alpha:1];
//            labelDay.textColor = [UIColor whiteColor];
//            labelDate.textColor = [UIColor whiteColor];
//            
//        } else {
//            
//            self.view.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
//        }
        return view;
    }
}

#pragma mark - tableView行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
        
    } else {
        
        return [self.modelWaypointsArr[section - 1] count];
    }
    
}
#pragma mark - tableView Cell赋值

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        KHHTravelNotesPageUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"user"];
        
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.modelUser = self.userModel;
        cell.modelNotes = self.noteModel;
        return cell;
        
    } else {
        
        KHHTravelNotesDetailPageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"notes"];
        
        //向cell传递indexpath 因为数据在当前页 协议点击方法需要数据的位置  又取不到section  和 row  所以需要传递进去  而不能在当前页传递是因为一次可能会出现多个cell  数据不准
        cell.indexpath = indexPath;
        
        //        //判断是是否有跳到地点详情的url是否有type
        //        cell.type = self.modelWaypointsArr
        
        cell.delegate = self; // location按钮代理人为当前controller
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        cell.backgroundColor = [UIColor colorWithRed:0.98 green:0.97 blue:0.93 alpha:1];
        cell.modelTravelNotes = self.noteModel;
        cell.modelUser = self.userModel;
        cell.modelWaypoint = self.modelWaypointsArr[indexPath.section - 1][indexPath.row];
        return cell;
    }
}



#pragma mark - 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 60 + (self.view.frame.size.width - 20) / 8 + 10 + 10 + 30 + 50 + 20;
    }
    else{
        KHHRecommendModel *tempModel = self.modelWaypointsArr[indexPath.section - 1][indexPath.row];
        CGFloat imgH = (tempModel.h).integerValue;
        CGFloat imgW = (tempModel.w).integerValue;
        
        CGFloat h = [[self class]heightWithText:tempModel.text fontSize:15 Width:CWIDTH - 40];
        // imgH * WIDTH / imgW + 10 + h + 10 + 15 + 10 白色背景图高度
        if (imgH!=0 && imgW != 0) {
            return imgH * CWIDTH / imgW + 10 + h + 10 + 15 + 10 + 20;
            
        } else {
            return 10 + h + 10 + 15 + 10 + 20;
        }
    }
}
#pragma mark - tableView选中方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark-滑动手势1
- (void)addScreenEdgePan
{
    UIScreenEdgePanGestureRecognizer *screenEdgePan = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(presentLeftMenuViewController:)];
    screenEdgePan.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:screenEdgePan];
    [self.tableView addGestureRecognizer:screenEdgePan];
   
}
#pragma mark-滑动手势2
-(void)presentLeftMenuViewController:(UIScreenEdgePanGestureRecognizer *)edge
{
    [self.navigationController popViewControllerAnimated:YES];
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
